'use strict';
const clients = require('../data/db_client.json');
const users = require('../data/db_user.json');
const cache = {};

module.exports = () => {
  class Model {
    async getClient(clientId, clientSecret) {
      let client = null;
      // 根据clientId获取客户信息
      clients.forEach(e => {
        if (e.clientId === clientId) {
          client = e;
          return;
        }
      });

      if (!client) {
        return false;
      }
      // 校验客户密钥
      if (clientSecret && clientSecret !== client.clientSecret) {
        return false;
      }
      return client;
    }
    async getUser(username, password) {
      let user;
      // 根据username获取用户信息
      users.forEach(e => {
        if (e.name === username) {
          user = e;
          return;
        }
      });

      if (!user) {
        return false;
      }
      if (user.password !== password) {
        return false;
      }
      return { userId: user.id };
    }

    async saveAuthorizationCode(code, client, user) {
      const _code = { ...code, client, user };
      cache['authCode-' + code.authorizationCode] = _code;
      return _code;
    }
    async getAuthorizationCode(authorizationCode) {
      const _code = cache['authCode-' + authorizationCode];
      if (!_code) return false;

      _code.expiresAt = new Date(_code.expiresAt);
      return _code;
    }
    async revokeAuthorizationCode(code) {
      delete cache['authCode-' + code.authorizationCode];
      return true;
    }

    async saveToken(token, client, user) {
      const _token = { ...token, client, user };

      cache['bearerToken-' + token.accessToken] = _token;
      cache['refreshToken-' + token.refreshToken] = _token;
      return _token;
    }
    async getAccessToken(bearerToken) {
      const _token = cache['bearerToken-' + bearerToken];
      if (!_token) return false;

      _token.accessTokenExpiresAt = new Date(_token.accessTokenExpiresAt);
      _token.refreshTokenExpiresAt = new Date(_token.refreshTokenExpiresAt);
      return _token;
    }
    async getRefreshToken(refreshToken) {
      const _token = cache['refreshToken-' + refreshToken];
      if (!_token) return false;

      _token.accessTokenExpiresAt = new Date(_token.accessTokenExpiresAt);
      _token.refreshTokenExpiresAt = new Date(_token.refreshTokenExpiresAt);
      return _token;
    }
    async revokeToken(token) {
      delete cache['refreshToken-' + token.refreshToken];
      return true;
    }
  }
  return Model;
};
